<template>
  <!-- 最上方的新增按钮 -->
  <div style="margin-bottom: 16px;">
    <el-button type="primary" @click="handleAdd">新增</el-button>
  </div>

  <!-- 循环生成卡片列表 -->
  <div v-for="item in dataList" :key="item.noteId" style="margin-bottom: 16px;">
    <el-card>
      <!-- 标题行，包含名称与日期 -->
      <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
        <span>{{ item.title }}</span>
        <span>{{ item.createTime }}</span>
      </div>

      <!-- 其他信息，如步数等 -->
      <div style="margin-bottom: 8px; white-space: pre-wrap;">
        内容：{{ item.content }}
      </div>


      <!-- 操作按钮 -->
      <div>
        <el-button type="text" @click="handleEdit(item)">编辑</el-button>
        <el-button type="text" @click="handleDelete(item.noteId)">删除</el-button>
      </div>
    </el-card>
  </div>
  <Dialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
    @on-close="onClose" @on-confirm="commit">
    <!-- 表单内容 -->
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
      <!-- 标题 -->
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>

      <!-- 内容（多行输入） -->
      <el-form-item label="内容" prop="content">
        <el-input type="textarea" rows="8" v-model="formData.content" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
import Dialog from '@/components/dialog/Dialog.vue'
import { ref, onMounted, reactive, nextTick } from 'vue'
import useDialog from '@/hooks/usedialog'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/store/islogin'
import { addNoteApi, updateNoteApi, getNoteApi, deleteNoteApi } from '@/api/note'
//获取用户信息store
const useUser =useUserStore()
//弹框参数
const { dialog, onClose, onConfirm, onShow } = useDialog()
//弹框提交按钮
const commit = async () => {
  if (dialog.title == "新增笔记") {
    if (useUser.user) {
      console.log(formData)
      formData.userId = useUser.user.userId
      const res = await addNoteApi(formData)
      if (res.code == 200) {
        ElMessage.success(res.msg)
        onClose()
        getNote()
      }
    }
  }
  if(dialog.title=="编辑笔记"){
    if(useUser.user){
      const res =await updateNoteApi(formData)
      if(res.code == 200){
        ElMessage.success(res.msg)
        onClose()
        getNote()
      }
    }
  }
}
// 引用表单实例（用于提交时的校验等）
const formRef = ref<FormInstance>()
// 表单数据
const formData = reactive({
  noteId:'',
  userId:'',
  title: '',
  content: '',
  createTime:'',
  updateTime:''
})
// 表单校验规则示例
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
})

interface DataItem {
  noteId: string
  userId: string
  title: string
  content: string
  createTime: string
  updateTime: string
}

// 列表数据
const dataList = ref<DataItem[]>([])
const getNote =async()=>{
  if(useUser.user){
    const res = await getNoteApi(useUser.user.userId)
    if(res.code==200){
      ElMessage.success(res.msg)
      dataList.value=res.data
    }
  }
}

// 新增
const handleAdd = () => {
  onShow()
  dialog.title='新增笔记'
    // 先清空表单数据
    Object.assign(formData, {
    noteId: '',
    userId: '',
    title: '',
    content: '',
    createTime: '',
    updateTime: ''
  });
  // 再调用表单重置方法（如 Element UI 的 resetFields）
  nextTick(() => {
    formRef.value?.resetFields();
  });
}

// 编辑
const handleEdit = (item: DataItem) => {
  // TODO: 在此编写编辑逻辑
  // 例如弹出编辑对话框、调用后端编辑接口等
  dialog.title="编辑笔记"
  onShow()
  Object.assign(formData,item)
  console.log(formData)
}

// 删除
const handleDelete = (noteId: string) => {
  ElMessageBox.confirm(
    '此操作将永久删除该项，是否继续？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const res = await deleteNoteApi(noteId)
    if(res.code==200){
      ElMessage.success(res.msg)
      getNote()
    }
  }).catch(() => {
    // 用户点击了取消，或关闭了对话框
    console.log('删除操作已取消');
  });
}

// 模拟在组件挂载后获取后端数据
onMounted(() => {
  getNote()
})
</script>

<style scoped>
/* 根据需要自定义一些样式 */
/* 根据需要调整表单间距等样式 */
.el-form-item {
  margin-bottom: 16px;
}
</style>